<template>
  <el-select
    style="width: 100%"
    v-model="scenicId"
    filterable
    remote
    clearable
    reserve-keyword
    placeholder="请选择关联预约景区"
    :remote-method="remoteMethod"
    :loading="loading"
    v-bind="$attrs"
  >
    <el-option
      v-for="item in scenicList"
      :key="item.scenicId"
      :label="item.scenicName"
      :value="item.scenicId"
    />
  </el-select>
</template>

<script>
// 获取企业景区列表
export default {
  name: 'CurrentScenic',
  props: ['value'],
  watch: {
    value: {
      immediate: true,
      handler (n) {
        this.scenicId = n
        this.valueChange(n)
      }
    },
    scenicId (n) {
      this.$emit('input', n)
    }
  },
  data () {
    return {
      scenicId: '',
      scenicList: [],
      loading: false
    }
  },
  created () {
    this.getList()
  },
  methods: {
    valueChange (n) {
      // 如果传入了一个id在本地列表里又没有，则查询
      if (n && !this.scenicList.some(_ => _.scenicId === n)) {
        this.getList({ scenicId: n })
      }
    },
    remoteMethod (scenicName) {
      this.getList({ scenicName })
    },
    getList (data = {}) {
      this.loading = true
      this.$POST('/sot-admin-api/scenic/queryCurrentScenicList', data).then(({ data }) => {
        let scenicList = data
        scenicList.length > 100 && (scenicList.length = 100)
        if (scenicList.length > 0) {
          if (data.scenicName) {
            this.scenicList = scenicList
          } else {
            // 排除已经存在的项
            let newList = scenicList.filter(item => !this.scenicList.some(_ => item.scenicId === _.scenicId))
            this.scenicList = [...newList, ...this.scenicList]
          }
        } else {
          this.scenicList = []
        }
      }).finally(_ => {
        this.loading = false
      })
    }
  }
}
</script>
